package cn.kzgg.basic.intercepter;

import cn.kzgg.basic.anno.PreAuthorize;
import cn.kzgg.basic.jwt.JwtUtils;
import cn.kzgg.basic.jwt.LoginResult;
import cn.kzgg.basic.jwt.Payload;
import cn.kzgg.basic.jwt.RsaUtils;
import cn.kzgg.basic.util.StrUtils;
import cn.kzgg.system.mapper.PermissionMapper;
import cn.kzgg.user.domain.Logininfo;
import cn.kzgg.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取U-TOKEN(也就是token)
        String token = request.getHeader("U-TOKEN");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //如果不为空
        if(StringUtils.hasLength(token)){
            /*//根据U-TOKEN从redis中获取登录信息
            Object loginTmp = redisTemplate.opsForValue().get(token);*/
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥解析jwt串
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            LoginResult loginResult = payload.getUserInfo();

            if (loginResult!=null) {
                //增加权限校验====即 登录之后，也需要查看是否有权限访问某个资源
                //1.区分是否是员工，是就需要校验权限
//                Logininfo logininfo = (Logininfo) loginTmp;
                Logininfo logininfo = loginResult.getLogininfo();
                if(logininfo.getType() == 0){//代表是员工，需要校验权限
                    //。得到当前请求的资源 url
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if(annotation != null){
                        String currentSn = annotation.value();//本次请求的sn
                        //。查询出当前登录人拥有的权限的资源 permissions
                        //List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
                        //。判断permissions是否包含url
                        if(!loginResult.getPermissions().contains(currentSn)){
                            //。 不包含。。提示权限不足，请联系管理员
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                        //。 包含。。放行（有权限访问）
                    }
                }
                //如果登录信息不为空，刷新过期时间，并登录放行
                //redisTemplate.opsForValue().set(token,loginTmp,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //2.返回登录
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;

    }
}
